<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
            <el-form-item label="商品名称" prop="productName">
                <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商品编号" prop="productSn">
                <el-input v-model="queryParams.productSn" placeholder="请输入商品编号" clearable style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商品分类" prop="productCategoryId">
                <el-select v-model="queryParams.productCategoryId" placeholder="请选择商品分类" clearable style="width: 200px">
                    <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
                        :value="item.categoryId" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="productId" />
            <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
            <el-table-column label="商品编号" align="center" prop="productSn" />
            <el-table-column label="价格" align="center" prop="price" />
            <el-table-column label="分类" align="center" prop="category.categoryName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination style="margin-top: 20px;" :total="total" v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize" :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" @size-change="getList" @current-change="getList" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="productFormRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="form.productName" placeholder="请输入商品名称" />
                </el-form-item>
                <el-form-item label="商品编号" prop="productSn">
                    <el-input v-model="form.productSn" placeholder="请输入商品编号" />
                </el-form-item>
                <el-form-item label="商品分类" prop="productCategoryId">
                    <el-select v-model="form.productCategoryId" placeholder="请选择商品分类">
                        <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
                            :value="item.categoryId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" />
                </el-form-item>
                <el-form-item label="商品描述" prop="productDescription">
                    <el-input v-model="form.productDescription" type="textarea" placeholder="请输入内容" />
                </el-form-item>
                <el-form-item label="图片URL" prop="imageUrl">
                    <el-input v-model="form.imageUrl" placeholder="请输入图片URL" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { listProduct, getProduct, addProduct, updateProduct, deleteProduct } from '@/api/product';
import { listCategory } from '@/api/category';

// 定义接口
interface Product {
    productId?: number;
    productName: string;
    productSn: string;
    productCategoryId: number | null;
    price: number;
    productDescription?: string;
    imageUrl?: string;
    category?: {
        categoryName: string;
    };
}

interface Category {
    categoryId: number;
    categoryName: string;
}

const loading = ref(true);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const open = ref(false);
const productList = ref<Product[]>([]);
const categoryOptions = ref<Category[]>([]);

const data = reactive({
    form: {
        productId: undefined,
        productName: '',
        productSn: '',
        productCategoryId: null,
        price: 0,
        productDescription: '',
        imageUrl: ''
    } as Product,
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        productSn: undefined,
        productCategoryId: undefined
    },
    rules: {
        productName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        productSn: [{ required: true, message: "商品编号不能为空", trigger: "blur" }],
        productCategoryId: [{ required: true, message: "请选择商品分类", trigger: "change" }],
        price: [{ required: true, message: "商品价格不能为空", trigger: "blur" }],
    } as FormRules
});

const { queryParams, form, rules } = toRefs(data);
const queryRef = ref<FormInstance>();
const productFormRef = ref<FormInstance>();

/** 查询商品列表 */
function getList() {
    loading.value = true;
    listProduct(queryParams.value).then(response => {
        // Adapt to backend response structure
        if (response.data && (response.data.list || response.data.rows || response.data.records)) {
            // Backend handles pagination
            productList.value = response.data.list || response.data.rows || response.data.records;
            total.value = response.data.total;
        } else if (Array.isArray(response.data)) {
            // Backend returns all data (filtered), perform frontend pagination
            const allData = response.data;
            total.value = allData.length;

            // Slice data for current page
            const currentPage = queryParams.value.pageNum;
            const pageSize = queryParams.value.pageSize;
            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            productList.value = allData.slice(start, end);
        } else {
            productList.value = [];
            total.value = 0;
        }
        loading.value = false;
    });
}/** 查询分类列表 */
function getCategoryList() {
    listCategory().then(response => {
        categoryOptions.value = response.data;
    });
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

/** 表单重置 */
function reset() {
    form.value = {
        productId: undefined,
        productName: '',
        productSn: '',
        productCategoryId: null,
        price: 0,
        productDescription: '',
        imageUrl: ''
    };
    productFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Product[]) {
    ids.value = selection.map(item => item.productId!);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加商品";
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
    reset();
    const productId = row.productId || ids.value[0];
    getProduct(productId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改商品";
    });
}

/** 提交按钮 */
function submitForm() {
    productFormRef.value?.validate(valid => {
        if (valid) {
            if (form.value.productId != undefined) {
                updateProduct(form.value).then(() => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addProduct(form.value).then(() => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row: any) {
    const productIds = row.productId ? [row.productId] : ids.value;
    ElMessageBox.confirm('是否确认删除商品编号为"' + productIds + '"的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        return deleteProduct(productIds);
    }).then(() => {
        getList();
        ElMessage.success("删除成功");
    }).catch(() => { });
}

onMounted(() => {
    getList();
    getCategoryList();
});
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.mb8 {
    margin-bottom: 8px;
}
</style>